import axios, {AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig, AxiosHeaders} from 'axios';
// 设置超时时间
const service: AxiosInstance = axios.create({
    // 设置一个请求基础地址
    baseURL: 'http://127.0.0.1:7000',
    timeout: 5000
});
// 请求
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);
// 返回
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            response.data;
            return response.data;
        } else {

            Promise.reject();
        }
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

/ 自定义POST方法，设置Content-Type为application/
service.post = function <T>(url: string, data?: any): Promise<T> {
    const headers = new AxiosHeaders();
    headers.set('Content-Type', 'application/json');
    const authorization = localStorage.getItem('Authorization');
    headers.set('Authorization', authorization);
    const config: InternalAxiosRequestConfig = {
        url,
        method: 'post',
        data,
        headers
    };
// 使用类型断言处理返回值
    return this.request(config);
};
// 自定义GET方法
// 自定义GET方法
service.get = function <T = any>(url: string, params?: any): Promise<T> {
    const headers = new AxiosHeaders();
    const authorization = localStorage.getItem('Authorization');
    headers.set('Authorization', authorization);
    const config: InternalAxiosRequestConfig = {
        url,
        method: 'get',
        params,
        headers
    };

    return this.request(config);
};
export default service;
